package com.example.animalcase;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.animalcase.bean.Note;

import java.text.SimpleDateFormat;
import java.util.Date;


public class WriteFragment extends Fragment {
    private EditText etTitle,etContent;
    private Button addButton;

    private NoteDbOpenHelper mNoteDbOpenHelper;

    private Context mContext;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = getActivity();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v= inflater.inflate(R.layout.fragment_write, container, false);

        etTitle=(EditText) v.findViewById(R.id.et_title);
        etContent=(EditText) v.findViewById(R.id.et_content);

        mNoteDbOpenHelper=new NoteDbOpenHelper(mContext);


        addButton=(Button)v.findViewById(R.id.add_button);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                add(v);
            }
        });

        return v;
    }
    public void add(View view){
        String title=etTitle.getText().toString();
        String content=etContent.getText().toString();
        if (TextUtils.isEmpty(title)){
            Toast.makeText(mContext,"标题不能为空",Toast.LENGTH_SHORT).show();
            return;
        }
        Note note=new Note();
        note.setTitle(title);
        note.setContent(content);
        note.setCreatedTime(getTime());
        long row=mNoteDbOpenHelper.insertDaate(note);
        if (row != -1){
            Toast.makeText(mContext,"添加成功",Toast.LENGTH_SHORT).show();
            etTitle.setText("");
            etContent.setText("");
        }else {
            Toast.makeText(mContext,"添加失败",Toast.LENGTH_SHORT).show();
        }
    }

    private String getTime(){
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("YYYY年MM月dd HH:mm:ss");
        Date date=new Date();
        return simpleDateFormat.format(date);

    }

}
